<!-- 业务关联-组件 -->
<template>
  <div>
    <formItemTable ref="formItemTable" :class="{notEdit:inputDisabled}" @open="openDialog"
                   v-on="$listeners" v-bind="$attrs" @cancel="cancel"
                   @clearSelect="clearSelect">
      <dt-dialog
        :title="title"
        append-to-body
        :visible.sync="visible"
        width="1350px"
        @closeDialog="cancel"
        @comfirmBtn="comfirm"
      >
        <dt-table
          v-if="refesh"
          ref="tableBusiness"
          v-loading="loading"
          :table-opts="tableOpts"
          :is-column-search="false"
          :pagination-data="{
            total: total,
            queryParams: filterForm
          }"
          @pagination="pagination"
          @searchReset="handleReset"
          @searchChange="handleQuery"
          @selection-change="handleSelectionChange"
          @current-change="handleCurrentChange"
        />
      </dt-dialog>
    </formItemTable>
    <!-- 详情弹框 -->
    <formDataDrawer ref="formDataDrawerRef" :form-json="formJson"
                    :formId="businessForm" @getDataList="getList" />
  </div>
</template>

<script>
import formDataDrawer from '../../components/formDataDrawer'
import formItemTable from '@/framework/components/form-item-table/index'
import { customFormDataGetList } from '@/framework/api/developerCenter/elementRightPanel.js'
import { customFormInfoDetail } from '@/framework/api/developerCenter/formDesignData'
import { getTableOptions } from '@/framework/views/developer-center/application-center/application-system/applicationFormDesign/build/generator/json-data'

export default {
  name: 'BusinessAssociat',
  components: { formItemTable, formDataDrawer },
  inject: {
    elForm: {
      default: ''
    },
    elFormItem: {
      default: ''
    }
  },
  props: {
    // 是否多选
    multiple: {
      type: Boolean,
      default: true
    },
    // 是否禁用
    disabled: {
      type: Boolean,
      default: false
    },
    // 操作列是否展示“详情”
    displayOperationDetail: {
      type: Boolean,
      default: false
    },
    // 关联的表单
    businessForm: {
      type: String,
      default: ''
    },
    value: {
      tpye: Array,
      default: () => {
        return []
      }
    }
  },
  data() {
    return {
      formJson: {},
      refesh: false,
      title: '选择',
      visible: false, // 弹窗是否展示
      // 遮罩层
      loading: false,
      // 总条数
      total: 0,
      // 查询参数
      filterForm: {
        pageNo: 1,
        pageSize: 10
      },
      tableOpts: {},
      multipleSelection: [],
      first: false
    }
  },
  computed: {
    inputDisabled() {
      return this.disabled || (this.elForm || {}).disabled
    },
    checkedObj() {
      return this.value.reduce((pre, item) => {
        pre[item.id] = item
        return pre
      }, {})
    },
    // 详情参数
    detailOption() {
      return {
        rows: this.tableOpts.tableCol || [],
        data: {}
      }
    }
  },
  mounted() {
    this.$nextTick(() => {
      const { showField } = this.$attrs
      const temp = (this.value || []).map((item) => {
        return { id: item.id, [showField]: this.singleOrMany(item[showField]) }
      })
      this.$refs.formItemTable.confirm(temp)
    })
  },
  methods: {
    clearSelect() {
      console.log('但是荆防颗粒电视剧')
      this.$emit('input', [])
    },
    openDialog(value) {
      this.visible = value
      this.tableOpts = {}
      if (!this.businessForm) { // 没有选择关联的表单，无法获取表单列表
        return
      }
      this.first = true
      this.$nextTick(() => {
        this.getTemplate()
      })
    },
    // 获取表格属性
    getTemplate() {
      this.refesh = false
      customFormInfoDetail(this.businessForm).then((res) => {
        const operatorBtn = this.displayOperationDetail ? [{
          text: '详情',
          size: 'small',
          click: (row, col, cellValue) => {
            this.$refs.formDataDrawerRef.handleOpen('detail', row)
          }
        }] : []
        this.formJson = JSON.parse(res.data.formContent)
        this.tableOpts = { ...getTableOptions(JSON.parse(res.data.formContent), [], []),
          firstTableCol: {
            select: this.multiple,
            width: 55
          },
          moreSearch: true,
          highlightCurrentRow: !this.multiple,
          operator: { operatorBtn }
        }
        this.getList()
        this.refesh = true
      })
    },
    // 单选
    handleCurrentChange(val) {
      !this.multiple && (this.multipleSelection = [val])
    },
    cancel() {
      const fn = this.multiple ? 'clearSelection' : 'setCurrentRow'
      this.$refs && this.$refs.tableBusiness && this.$refs.tableBusiness[fn]()
      // this.multiple ? (this.$refs?.tableBusiness.clearSelection()) : this.$refs.tableBusiness.setCurrentRow();
      this.visible = false
      this.total = 0
      // 查询参数
      this.filterForm = {
        pageNo: 1,
        pageSize: 10
      }
      this.tableOpts = {}
      this.multipleSelection = []
    },
    comfirm() {
      // console.log('第三方就开始兑积分', this.$attrs)
      const selectValue = []
      const selectLabelList = []
      const { showField } = this.$attrs

      this.multipleSelection.forEach((item) => {
        selectValue.push({ id: item.id, [showField]: item[showField], formId: this.businessForm })
        selectLabelList.push({ id: item.id, [showField]: this.singleOrMany(item[showField]) })
      })
      this.$refs.formItemTable.confirm(selectLabelList)
      this.$emit('input', selectValue)
      this.cancel()
    },
    singleOrMany(modelValue, mes = '-') {
      const list = ['', null, undefined]
      // 判空
      if (list.includes(modelValue) || (Array.isArray(modelValue) && modelValue.length === 0)) {
        return mes
      }
      // 单选、多选、选择框、级联框
      if (this.$attrs.options && this.$attrs.options.length) {
        let val = ''// [1,2]
        switch (Object.prototype.toString.call(modelValue)) {
          case ('[object Array]'): val = modelValue; break
          case ('[object String]'): val = modelValue.split(','); break
          default: val = [modelValue]
        }
        const label = 'label'
        const value = 'value'
        const selectVal = (this.$attrs.options || []).reduce((pre, child) => {
          (val.includes(child[value])) && (pre = pre ? `${pre},${child[label]}` : child[label])
          return pre
        }, '') // '男,女'
        return selectVal
      } else {
        return modelValue
      }
    },
    // 多选框选中数据
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    // 获取表格数据
    getList() {
      this.loading = true
      const { pageNo, pageSize, ...searchParams } = this.filterForm
      // configPagination 是否分页，1是，2否
      customFormDataGetList({ searchParams, pageNo, pageSize, formId: this.businessForm, configPagination: 1 }).then((res) => {
        this.loading = false
        this.tableOpts.tableData = res.data.rows || []
        this.total = res.data.totalRows
        if (this.multiple) {
          this.tableToggleRow()
        } else {
          this.tableSingle()
        }
      })
    },
    tableSingle() {
      // 单选
      if (this.first) {
        this.first = false
        if (!this.value.length) { return }
        const selectValue = this.tableOpts.tableData.filter((item) => item.id === this.value[0].id)
        this.$refs.tableBusiness.setCurrentRow(selectValue.length ? selectValue[0] : this.value[0])
      } else {
        this.$refs.tableBusiness.setCurrentRow(this.multipleSelection.length ? this.multipleSelection[0] : null)
      }
    },
    tableToggleRow() {
      if (!this.first) {
        return
      }
      this.first = false
      if (!this.value.length) {
        return
      }
      this.$nextTick(() => {
        const temp = []
        // table反显第一页选中状态
        this.tableOpts.tableData.forEach((element) => {
          if (this.checkedObj[element.id]) {
            temp.push(element.id)
            this.$refs.tableBusiness.toggleRowSelection(element, true)
          }
        })
        // 反显其他页面选中状态
        Object.keys(this.checkedObj).forEach((id) => {
          !temp.includes(id) && this.$refs.tableBusiness.toggleRowSelection(this.checkedObj[id], true)
        })
      })
    },
    /** 搜索按钮操作 */
    handleQuery(formModel) {
      this.filterForm = { ...this.filterForm, ...formModel }
      // this.$refs.resourceTable.clearSelection()
      this.filterForm.pageNo = 1
      this.getList()
    },
    /** 重置按钮操作 */
    handleReset() {
      this.filterForm = {
        pageNo: 1,
        pageSize: 10
      }
      this.handleQuery()
    },
    pagination() {
      this.getList(this.filterForm)
    }
  }
}
</script>

  <style lang="scss" scoped>
  .dt-table-select{
      .select-tag {
      border: 1px #c0c4cc solid;
      border-radius: 5px;
      cursor: pointer;
      width: 100%;
      height: 100%;
      padding: 0px 8px 0 8px;
      margin: auto;
      min-height: 36px;
      line-height: 36px;
      min-width: 200px;

      > div {
        margin: auto;
      }

      .el-tag {
        margin-right: 5px;
        margin-bottom: 4px;
      }
    }

    .isDisabled {
      background-color: #f5f7fa;
      border-color: #e4e7ed;
      color: #c0c4cc;
      cursor: not-allowed;
    }

    .plactext {
      color: #dcdfe6;
    }
  }
  .dt-table-select.notEdit{
    position: relative;
    &::after{
      content: '';
      position: absolute;
      top:0;
      left:0;
      width: 100%;
      height: 100%;
      // background: red;
    }
    ::v-deep .tag-box{
      background-color: #f5f7fa;
      border-color: #e4e7ed;
      color: #c0c4cc;
      cursor: not-allowed;
    }
  }

  </style>

